<?php
namespace App\Admin\Controllers\Products;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\SupplierM;
use App\Models\Product\ProductMaterial;
use App\Models\Product\ProductMaterialApplicationClassify;
use App\Models\Product\ProductMaterialClassifyMax;
use App\Models\Product\ProductMaterialClassifyMin;
use App\Models\Product\ProductMaterialContainer;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;

class MaterialListController extends AdminController{

    protected $title = '材料说明书';

    protected function grid()
    {
        $grid = new Grid(new ProductMaterial());
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('id','ID');
        $grid->column('material_code','材料编码');
        $grid->column('title','材料名称');
        $grid->column('title1','材料名称(材质)');
        $grid->column('title2','材料名称(规格)');
        $grid->column('title3','材料名称(工艺/功能)');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->material_classify_max_title = $item->material_classify_max->title ?? '';
                $item->material_classify_min_title = $item->material_classify_min->title ?? '';
            }
            return $collection;
        });
        $grid->column('material_application_classify_id','应用品类')->display(function ($value){
            $arr = [];
            if(!empty($value)){
                foreach ($value as $key => $id){
                    $arr[] = ProductMaterialApplicationClassify::getValueById($id,'title');
                }
            }
            return $arr ? implode('、', $arr) : '';
        });
        $grid->column('material_classify_max_title','材料大类');
        $grid->column('material_classify_min_title','材料小类');

        $grid->column('supplier.code','在库供应商编码');
        $grid->column('supplier.name','在库供应商名称');
        $grid->column('supplier_title','(临时)供应商名称');


        $grid->column('quote_price','报价');
        $grid->column('quote_currency','报价单位')->display(function ($value) {
            return $value ? ProductMaterial::$_quote_currency[$value] : '';
        });
        $grid->column('function','功能性');
        $grid->column('container_no','货柜号')->display(function ($value){
            $arr = [];
            if(!empty($value)){
                foreach ($value as $key => $id){
                    $arr[] = ProductMaterialContainer::getValueById($id,'code');
                }
            }
            return $arr ? implode('、', $arr) : '';
        });
        $grid->column('test_remark','测试标准和要求');
        $grid->column('test_data','测试数据');
        $grid->column('test_after','后整理');
        $grid->column('composition','成分');
        $grid->column('spec','规格参数信息');
        $grid->column('yarn_count','纱支');
        $grid->column('weight','克重(g/㎡)');
        $grid->column('door_width','门幅');
        $grid->column('door_unit','门幅单位');
        $grid->column('specification','规格');
        $grid->column('unit','单位');
        $grid->column('coloring_cycle','打色周期');
        $grid->column('devlop_moq','开发MOQ（米）');
        $grid->column('devlop_cylce','开发周期（天）');
        $grid->column('moq','大货MOQ（米）');
        $grid->column('cylce','大货周期（天）');
        $grid->column('grey_cloth','坯布数量（米）');
        $grid->column('admin_id','建档人')->display(function ($value){
            return $value ? User::getUsernameById($value) : '';
        });
        $grid->column('created_at','建档时间');
        $grid->column('review_status','品质评审')->bool([ProductMaterial::REVIEW_YES => true, ProductMaterial::REVIEW_NO => false]);
        $grid->column('status','是否使用')->bool([ProductMaterial::STATUS_YES => true, ProductMaterial::STATUS_NO => false]);

        $grid->paginate(10);
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('products/material-list-download'));
        });
        $grid->disableActions();
        $grid->disableBatchActions();
        $grid->disableCreateButton();
        $grid->fixColumns(3,-2);
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter){
                $filter->disableIdFilter(false);
                $filter->where(function ($query) {
                    $query->where('material_code', 'like', "%{$this->input}%")
                        ->orWhere('title', 'like', "%{$this->input}%");
                }, '查询','material8')->placeholder('模糊查询材料编码、名称');
                $filter->contains('material_application_classify_id', '应用品类')->select(ProductMaterialApplicationClassify::options());
                $filter->in('status', '状态')->checkbox(ProductMaterial::$_status);
            });
            $filter->column(1/2, function ($filter) {
                $filter->equal('material_classify_max_id', '材料大类')->select(ProductMaterialClassifyMax::options());
                $filter->equal('material_classify_min_id', '材料小类')->select(ProductMaterialClassifyMin::options());
                //$filter->equal('admin_id','建档人')->select(User::getCUserOptions());
                $filter->where(function ($query) {
                    $query->where('supplier_title', 'like', "%{$this->input}%");
                }, '临时、在库供应商名称查询','supplier8')->placeholder('模糊查询临时、在库供应商名称');
                $filter->equal('supplier_id', '在库材料供应商')->select(SupplierM::options());
            });
        });

        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ProductMaterial::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'material8'){
                $query->where(function ($query) use($_filter){
                    $query->where('material_code', 'like', "%{$_filter}%")
                        ->orWhere('title', 'like', "%{$_filter}%");
                });
            }
            if($key == 'supplier8'){
                $query->where(function ($query) use($_filter){
                    $query->where('supplier_title', 'like', "%{$_filter}%");
                });
            }
            if($key == 'material_application_classify_id'){
                $query->where(function ($query) use($_filter){
                    $query->where('material_application_classify_id', 'like', "%{$_filter}%");
                });
            }
            if(in_array($key,['status'])){
                $query->whereIn($key,$_filter);
            }
            if(in_array($key,[
                'material_classify_max_id',
                'material_classify_min_id',
                'supplier_id',
                'admin_id',
            ])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }


    private function _exeDownload($query){
        $head = ['材料编码','材料名称','材料名称(材质)','材料名称(规格)','材料名称(工艺/功能)','应用品类','材料大类','材料小类',
            '在库材料供应商编码','在库材料供应商名称','(临时)供应商名称','报价','报价单位','功能性','货柜号',
            '测试标准和要求','测试数据','后整理','成分','规格参数信息','纱支','克重(g/㎡)','门幅','门幅单位','规格','单位',
            '打色周期','开发MOQ（米）','开发周期（天）','大货MOQ（米）','大货周期（天）','坯布数量（米）',
            '品质评审','是否启用','建档人','建档时间'];
        RExcel::exportCsv('材料列表', function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res){

        $containerArr = ProductMaterialContainer::options()->toArray();
        $classifyArr = ProductMaterialApplicationClassify::options()->toArray();
        foreach ($res as $model){
            //柜号
            $containerStr = '';
            if($model->container_no){
                $container = [];
                foreach ($model->container_no as $key => $containerId){
                    $container[] = $containerArr[$containerId];
                }
                $containerStr = implode('、', $container);
            }
            //品类
            $classifyStr = '';
            if($model->material_application_classify_id){
                $arr = [];
                foreach ($model->material_application_classify_id as $key => $id){
                    $arr[] = $classifyArr[$id];
                }
                $classifyStr = implode('、', $arr);
            }
            $temp = [
                $model->material_code ?? '',
                $model->title ?? '',
                $model->title1 ?? '',
                $model->title2 ?? '',
                $model->title3 ?? '',
                $classifyStr,
                $model->material_classify_max->title ?? '',
                $model->material_classify_min->title ?? '',
                $model->supplier->code ?? '',
                $model->supplier->name ?? '',
                $model->supplier_title ?? '',
                $model->quote_price ?? 0,
                $model->quote_currency ? ProductMaterial::$_quote_currency[$model->quote_currency] : '',
                $model->function ?? '',
                $containerStr,
                $model->test_remark ?? '',
                $model->test_data ?? '',
                $model->test_after ?? '',
                $model->composition ?? '',
                $model->spec ?? '',
                $model->yarn_count ?? '',
                $model->weight ?? '',
                $model->door_width ?? '',
                $model->door_unit ?? '',
                $model->specification ?? '',
                $model->unit ?? '',
                $model->coloring_cycle ?? '',
                $model->devlop_moq ?? '',
                $model->devlop_cylce ?? '',
                $model->moq ?? '',
                $model->cylce ?? '',
                $model->grey_cloth ?? '',
                ProductMaterial::$review_status[$model->review_status] ?? '',
                ProductMaterial::$_status[$model->status] ?? '',
                User::getUsernameById($model->admin_id) ?? '',
                $model->created_at,
            ];
            yield $temp;
        }
    }

}
